package com.cgy.utils.spider.config;

import java.util.List;

import com.cgy.utils.spider.callback.AbstractCallBack;
import com.cgy.utils.spider.cookie.Cookie;
import com.cgy.utils.spider.cookie.Cookies;
import com.cgy.utils.spider.header.Header;
import com.cgy.utils.spider.header.Headers;

import lombok.Getter;
import lombok.Setter;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.downloader.AbstractDownloader;

/**
 * webmagic初始化基础配置
 * 
 * @author CH
 *
 */
@Getter
@Setter
public class WebMagicConfig extends AbstractConfig {

	private AbstractDownloader downloader;
	private Request request = new Request();
	
	private Site site;
	private int thread;
	private AbstractCallBack callback;

	public WebMagicConfig() {
		this.site = Site.me();
		this.site.setCharset("UTF-8").setUseGzip(true).setCycleRetryTimes(3).setTimeOut(10 * 1000)
				.setSleepTime(10 * 1000);
	}

	public static WebMagicConfig create() {
		return new WebMagicConfig();
	}

	@Override
	public AbstractConfig addCookieConfig(Cookie cookie) {
		this.request.addCookie(cookie.getCookieKey(), cookie.getCookieVal());
		this.site.addCookie(cookie.getCookieKey(), cookie.getCookieVal());
		return this;
	}

	@Override
	public AbstractConfig addCookieConfig(Cookies cookies) {
		List<Cookie> lCookies = cookies.getCookie();
		for (Cookie cookie : lCookies) {
			this.site.addCookie(cookie.getCookieKey(), cookie.getCookieVal());
			this.request.addCookie(cookie.getCookieKey(), cookie.getCookieVal());
		}
		return this;
	}

	@Override
	public AbstractConfig addHeaderConfig(Header header) {
		this.site.addHeader(header.getHeaderKey(), header.getHeaderVal());
		this.request.addHeader(header.getHeaderKey(), header.getHeaderVal());
		return this;
	}

	@Override
	public AbstractConfig addHeaderConfig(Headers headers) {
		List<Header> lHeaders = headers.getHeader();
		for (Header header : lHeaders) {
			this.site.addHeader(header.getHeaderKey(), header.getHeaderVal());
			this.request.addHeader(header.getHeaderKey(), header.getHeaderVal());
		}
		return this;
	}

	@Override
	public AbstractConfig callback(AbstractCallBack abstractCallBack) {
		this.callback = abstractCallBack;
		return this;
	}

	@Override
	public AbstractConfig charset(String charset) {
		this.site.setCharset(charset);
		this.request.setCharset(charset);
		return this;
	}

	@Override
	public AbstractConfig domain(String domain) {
		this.site.setDomain(domain);
		return this;
	}

	@Override
	public AbstractConfig cycleRetryTimes(int cycle) {
		this.site.setCycleRetryTimes(cycle);
		return this;
	}

	@Override
	public AbstractConfig timeout(int timeout) {
		this.site.setTimeOut(timeout);
		return this;
	}

	@Override
	public AbstractConfig sleeptime(int sleeptime) {
		this.site.setSleepTime(sleeptime);
		return this;
	}

	@Override
	public AbstractConfig thread(int thread) {
		this.thread = thread;
		return this;
	}

}
